#!/usr/bin/python

try:
	from ConfigParser import SafeConfigParser as ConfigParser
except ImportError:
	from ConfigParser import ConfigParser

import os
CONFIG_FILE = os.path.join(os.environ['HOME'], '.wjs.ini')

import gdata.calendar.service
import gdata.calendar
import atom

import db

def login(user, password):
	calendar_service = gdata.calendar.service.CalendarService()
	calendar_service.email = user
	calendar_service.password = password
	calendar_service.source = 'Google-Calendar_Python_Sample-1.0'
	calendar_service.ProgrammaticLogin()
	return calendar_service

def GetCalendar(calendar_service, name):
	feed = calendar_service.GetOwnCalendarsFeed()
	for i, calendar in enumerate(feed.entry):
		if calendar.title.text == name:
			return calendar
	calendar = gdata.calendar.CalendarListEntry()
	calendar.title = atom.Title(text=name)
	calendar.where = gdata.calendar.Where(value_string='Paris')
	calendar.color = gdata.calendar.Color(value='#2952A3')
	calendar.timezone = gdata.calendar.Timezone(value='Europe/Paris')
	calendar.hidden = gdata.calendar.Hidden(value='false')
	new_calendar = calendar_service.InsertCalendar(new_calendar=calendar)
	return new_calendar

def GetCalendarEvents(calendar_service, calendar):
	feed = calendar_service.GetCalendarEventFeed(calendar.GetAlternateLink().href)
	events = {}
	deletes = []
	def add_feed_events(feed):
		for i, event in enumerate(feed.entry):
			title = event.title.text
			if events.has_key(title):
				deletes.append(event.GetEditLink().href)
			else:
				events[title] = event
	while True:
		add_feed_events(feed)
		if feed.GetNextLink():
			feed = calendar_service.GetCalendarEventFeed(feed.GetNextLink().href)
		else:
			break
	for uri in deletes:
		calendar_service.DeleteEvent(uri)
	return events

def GetNextEpisodeCalendar(url):
	f = urlopen(url)
	cal = readCalendar(f)
	f.close()
	return cal

def UpdateCalendarEvents(calendar_service, calendar):
	events = GetCalendarEvents(calendar_service, calendar)
	print "%d existing events" % len(events.keys())
	uri = calendar.GetAlternateLink().href

	updated, added = 0, 0

	for game in db.Game.select("release_date IS NOT NULL"):
		platform = game.platform.shortName or game.platform.name
		summary = "%s (%s)" % (game.name, platform)

		if events.has_key(summary):
			event = events[summary]
			update = True
		else:
			event = gdata.calendar.CalendarEventEntry()
			event.title = atom.Title(text=summary)
			update = False

		start_time = game.releaseDate.strftime("%Y-%m-%d")
		end_time = start_time
		while len(event.when) > 0:
			event.when.pop()
		event.when.append(gdata.calendar.When(start_time=start_time, end_time=end_time))

		if update:
			calendar_service.UpdateEvent(event.GetEditLink().href, event)
			updated += 1
		else:
			calendar_service.InsertEvent(event, uri)
			added += 1
	print "%d events updated, %d added" % (updated, added)

def main(conf = CONFIG_FILE):
	config = ConfigParser()
	config.read(conf)
	db.init(config.get("dsn", "games"))
	calendar_service = login(config.get("google-account", "name"), config.get("google-account", "password"))
	calendar = GetCalendar(calendar_service, config.get("calendars", "games"))
	UpdateCalendarEvents(calendar_service, calendar)

if __name__ == '__main__':
	main()
